package middleware

import (
	"gomain/app/model"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

func Auth(r *ghttp.Request) {
	ctx := r.GetCtx()

	if r.URL.Path == "/api/user/login" {
		g.Log().Debug(ctx, "跳过登录接口的认证")
		r.Middleware.Next()
		return
	}

	userVar, _ := r.Session.Get("user")
	if userVar == nil {
		g.Log().Warning(ctx, "未携带token", "path", r.URL.Path)
		r.Response.WriteJson(g.Map{
			"code": 401,
			"msg":  "未登录",
		})
		r.Exit()
	}

	// 类型转换
	var user *model.User
	if err := userVar.Scan(&user); err != nil {
		g.Log().Warning(ctx, "用户数据类型错误", "path", r.URL.Path, "error", err.Error())
		r.Response.WriteJson(g.Map{
			"code": 401,
			"msg":  "未登录",
		})
		r.Exit()
	}

	// 将用户ID保存到上下文中
	r.SetCtxVar("user_id", user.Id)

	g.Log().Debug(ctx, "认证通过", "path", r.URL.Path)
	r.Middleware.Next()
}
